from django.utils import timezone
from drf_yasg.utils import swagger_serializer_method
from rest_framework import serializers

from lab.user.models import ExtendedUser


class ExtendedUserSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    email = serializers.SerializerMethodField()
    is_wechat_linked = serializers.SerializerMethodField()
    avatar = serializers.CharField(max_length=100, required=False)
    phone_number = serializers.CharField(max_length=16, required=False)
    email_notifications_enabled = serializers.BooleanField(required=False)
    language = serializers.IntegerField(required=False)
    vip_expired_time = serializers.SerializerMethodField()
    is_vip_expired = serializers.SerializerMethodField()

    @swagger_serializer_method(serializer_or_field=serializers.CharField)
    def get_user_name(self, obj):
        return obj.user.username

    @swagger_serializer_method(serializer_or_field=serializers.CharField)
    def get_email(self, obj):
        return obj.user.email

    @staticmethod
    def get_is_wechat_linked(obj):
        return True if obj.union_id else False

    @staticmethod
    def get_vip_expired_time(obj):
        return int(obj.vip_expired_time.timestamp()) * 1000

    @staticmethod
    def get_is_vip_expired(obj):
        return True if obj.vip_expired_time < timezone.now() else False

    class Meta:
        model = ExtendedUser
        fields = (
            'id', 'avatar', 'user_name', 'phone_number', 'email', 'is_wechat_linked', 'email_notifications_enabled',
            'language', 'is_vip_expired', 'vip_expired_time', 'is_first_payment')

    def update(self, instance, validated_data):
        instance.user.username = self.initial_data.get('user_name', instance.user.username)
        instance.user.email = self.initial_data.get('email', instance.user.email)
        instance.user.save()

        instance.avatar = validated_data.get('avatar', instance.avatar)
        instance.phone_number = validated_data.get('phone_number', instance.phone_number)
        instance.email_notifications_enabled = validated_data.get('email_notifications_enabled',
                                                                  instance.email_notifications_enabled)
        instance.language = validated_data.get('language', instance.language)
        instance.save()
        return instance
